package com.bp.api.post;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.bp.vo.CommentsVO;
import com.bp.vo.PostVO;
import com.bp.vo.UserInfoVO;
import com.common.enums.CommonCode;
import com.common.enums.SystemStatusEnum;
import com.common.model.PageModel;
import com.common.utils.UploadUtil;
import com.idp.biz.bpcomments.entity.BpComments;
import com.idp.biz.bpcomments.service.BpCommentsService;
import com.idp.biz.bppost.entity.BpPost;
import com.idp.biz.bppost.service.BpPostService;
import com.idp.biz.bpuser.entity.BpUser;
import com.idp.biz.bpuser.service.BpUserService;
import com.vdurmont.emoji.EmojiParser;

/**
 * 帖子
 */
@RestController
@RequestMapping(value = "/api/post/", method = RequestMethod.POST)
public class PostController {
    private static Logger logger = LoggerFactory.getLogger(PostController.class);

    @Autowired
    private BpUserService userService;
    @Autowired
    private BpPostService postService;
    @Autowired
    private BpCommentsService commentsService;

    @Autowired
    private StringRedisTemplate redis;

    /**
     * 分页查询（无参数时，分页查询所有帖子；channelId有值时，查询频道相关帖子）
     */
    @CrossOrigin
    @RequestMapping(value = "/list")
    public String list(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        PageModel<BpPost> page = new PageModel<>();
        try {
            Integer draw = StringUtils.isNotEmpty(request.getParameter("draw")) ? Integer.valueOf(request.getParameter("draw")) : 0;//页号
            Integer length = StringUtils.isNotEmpty(request.getParameter("length")) ? Integer.valueOf(request.getParameter("length")) : 0;//每页条数
            //Integer recordsFiltered = StringUtils.isNotEmpty(request.getParameter("recordsFiltered")) ? Integer.valueOf(request.getParameter("recordsFiltered")) : 0 ;//过滤后总条数
            Integer recordsTotal = StringUtils.isNotEmpty(request.getParameter("recordsTotal")) ? Integer.valueOf(request.getParameter("recordsTotal")) : 0;//总条数
            Integer start = StringUtils.isNotEmpty(request.getParameter("start")) ? Integer.valueOf(request.getParameter("start")) : 0;//起始条数
            page.setDraw(draw);
            page.setLength(length);
            // page.setRecordsFiltered(recordsFiltered);
            page.setRecordsTotal(recordsTotal);
            page.setStart(start);

            String channelId = request.getParameter("channelId");
            String token = request.getParameter("token");
            BpPost bpPost = new BpPost();
            BpUser user = new BpUser();
            if (StringUtils.isNotEmpty(channelId)) {
                bpPost.setChannelId(channelId);
            }
            bpPost.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            if (StringUtils.isNotEmpty(token)) {
                user = userService.getByToken(token);
            }

            PageModel<BpPost> pageData = postService.findByPage(bpPost, page);
            List<BpPost> postList = pageData.getData();
            List<PostVO> postVoList = new ArrayList<PostVO>();
            if (postList != null && postList.size() > 0) {
                for (BpPost post : postList) {
                    BpComments comments = new BpComments();
                    comments.setPostId(post.getId());
                    comments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
                    List<BpComments> commentsList = commentsService.findBySearch(comments);
                    List<CommentsVO> commentsVoList = commentsToVo(user, commentsList);
                    PostVO postVO = getPostVo(post, user, commentsVoList);
                    postVoList.add(postVO);
                }
            }
            PageModel<PostVO> data = new PageModel<>();
            data.setData(postVoList);
            data.setDraw(pageData.getDraw());
            data.setLength(pageData.getLength());
            // data.setRecordsFiltered(recordsFiltered);
            data.setRecordsTotal(pageData.getRecordsTotal());
            data.setStart(pageData.getStart());

            json.put("data", data);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toJSONString();
    }

    /**
     * 帖子详情
     */
    @CrossOrigin
    @RequestMapping("/detail")
    public String detail(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String postId = request.getParameter("postId");
            String token = request.getParameter("token");
            if (StringUtils.isEmpty(postId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            BpPost post = postService.getDataById(postId);
            if (post == null) {
                json.put("code", SystemStatusEnum.CONTENT_IS_NULL.getValue());
                json.put("message", "帖子" + SystemStatusEnum.CONTENT_IS_NULL.getName());
                return json.toString();
            }

            BpUser user = userService.getByToken(token);
            BpComments comments = new BpComments();
            comments.setPostId(post.getId());
            comments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            List<BpComments> commentsList = commentsService.findBySearch(comments);
            List<CommentsVO> commentsVoList = commentsToVo(user, commentsList);
            PostVO postVO = getPostVo(post, user, commentsVoList);

            json.put("data", postVO);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 用户帖子列表
     */
    @CrossOrigin
    @RequestMapping("/userPostList")
    public String userPostList(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        PageModel<BpPost> page = new PageModel<>();
        try {
            Integer draw = StringUtils.isNotEmpty(request.getParameter("draw")) ? Integer.valueOf(request.getParameter("draw")) : 0;//页号
            Integer length = StringUtils.isNotEmpty(request.getParameter("length")) ? Integer.valueOf(request.getParameter("length")) : 0;//每页条数
            //Integer recordsFiltered = StringUtils.isNotEmpty(request.getParameter("recordsFiltered")) ? Integer.valueOf(request.getParameter("recordsFiltered")) : 0 ;//过滤后总条数
            Integer recordsTotal = StringUtils.isNotEmpty(request.getParameter("recordsTotal")) ? Integer.valueOf(request.getParameter("recordsTotal")) : 0;//总条数
            Integer start = StringUtils.isNotEmpty(request.getParameter("start")) ? Integer.valueOf(request.getParameter("start")) : 0;//起始条数
            page.setDraw(draw);
            page.setLength(length);
            // page.setRecordsFiltered(recordsFiltered);
            page.setRecordsTotal(recordsTotal);
            page.setStart(start);

            String type = request.getParameter("type");
            String token = request.getParameter("token");
            String userId = request.getParameter("userId");
            if (StringUtils.isEmpty(type)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            BpUser myUser = new BpUser();
            List<PostVO> postVoList = new ArrayList<>();
            BpPost bpPost = new BpPost();
            if (type.equals("1")) {
                String isLogin = redis.opsForValue().get(token);
                if (StringUtils.isEmpty(isLogin)) {
                    json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                    json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                    return json.toString();
                }
                myUser = userService.getByToken(token);
                BpUser othersUser = new BpUser();
                if (myUser == null) {
                    json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
                    json.put("message", SystemStatusEnum.USER_IS_NULL.getName());
                    return json.toJSONString();
                }
                //我的北漂，通过token查询当前登录用户数据，关联查询该用户帖子数据
            	bpPost.setUserId(myUser.getId());
            } else if (type.equals("2")) {
                //他人北漂，通过userId查询他人用户数据，关联查询他人帖子数据，并带入当前登录用户的id，用于关联评论点赞列表
                BpUser othersUser = userService.getById(userId);
            	if (othersUser == null) {
            		json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
            		json.put("message", "目标" + SystemStatusEnum.USER_IS_NULL.getName());
            		return json.toJSONString();
            	}
            	bpPost.setUserId(othersUser.getId());
            }
            bpPost.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());

            BpComments comments = new BpComments();
            comments.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            List<BpComments> commentsList = commentsService.findBySearch(comments);

            PageModel<BpPost> pageData = postService.findByPage(bpPost, page);
            List<BpPost> postList = pageData.getData();
            for (BpPost post : postList) {
                PostVO postVo = new PostVO();
                List<CommentsVO> commentsVoList = commentsToVo(myUser, commentsList);
                postVo = getPostVo(post, myUser, commentsVoList);
                postVoList.add(postVo);
            }
            PageModel<PostVO> data = new PageModel<>();
            data.setData(postVoList);
            data.setDraw(pageData.getDraw());
            data.setLength(pageData.getLength());
            // data.setRecordsFiltered(recordsFiltered);
            data.setRecordsTotal(pageData.getRecordsTotal());
            data.setStart(pageData.getStart());

            json.put("data", data);
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
            return json.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 发帖
     */
    @CrossOrigin
    @RequestMapping("/publish")
    public String publish(@RequestParam("images") List<MultipartFile> images, HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String token = request.getParameter("token");
            String content = request.getParameter("content");
            String channelId = request.getParameter("channelId");
            String channelName = request.getParameter("channelName");
            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(content) || StringUtils.isEmpty(channelId) || StringUtils.isEmpty(channelName)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            String isLogin = redis.opsForValue().get(token);
            if (StringUtils.isEmpty(isLogin)) {
                json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);
            if (user == null) {
                json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
                json.put("message", SystemStatusEnum.USER_IS_NULL.getName());
                return json.toJSONString();
            }

            String imagesPath = "";
            if (images != null && images.size() > 9) {
                json.put("code", SystemStatusEnum.IMAGES_SIZE_IS_TOO_LONG.getValue());
                json.put("message", SystemStatusEnum.IMAGES_SIZE_IS_TOO_LONG.getName());
                return json.toJSONString();
            } else if (images != null && images.size() > 0) {
                for (MultipartFile image : images) {
                    // 文件命名
                    String originalFilename = image.getOriginalFilename();
                    if (StringUtils.isNotBlank(originalFilename)) {
                        // 获取文件的后缀名
                        String extendName = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                        // 判断文件是否是图片
                        String[] imagType = {".jpg", ".png", ".bmp", ".gif"};
                        List<String> imageTyepLists = Arrays.asList(imagType);

                        if (imageTyepLists.contains(extendName)) {
                            try {
                                imagesPath += UploadUtil.uploadImage(image) + ",";
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                                json.put("code", SystemStatusEnum.SERVERERROR.getValue());
                                json.put("message", SystemStatusEnum.SERVERERROR.getName());
                                return json.toString();
                            } catch (IOException e) {
                                e.printStackTrace();
                                json.put("code", SystemStatusEnum.SERVERERROR.getValue());
                                json.put("message", SystemStatusEnum.SERVERERROR.getName());
                                return json.toString();
                            }
                        } else {
                            json.put("code", SystemStatusEnum.IMAGES_FORMAT_IS_ERROE.getValue());
                            json.put("message", SystemStatusEnum.IMAGES_FORMAT_IS_ERROE.getName());
                        }
                    }
                }
            }

            BpPost post = new BpPost();
            post.setUserId(user.getId());
            post.setImages((imagesPath == "" ? "" : imagesPath.substring(0, imagesPath.length() - 1)));
            String emojiParserContent = EmojiParser.parseToAliases(content);
            logger.debug("表情符号转换-->emojiParserContent:{}", emojiParserContent);
            post.setContent(content);
            //post.setContent(EmojiParser.parseToAliases(content));
            post.setChannelId(channelId);
            post.setChannelName(channelName);
            post.setPraiseNum(0);
            post.setIsClassic("0");
            post.setIsTop("0");
            post.setReleaseTime(new Date());
            post.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            post.setSymbol(CommonCode.Y.getValue());
            postService.add(post);

            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 删帖
     */
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request) {
        JSONObject json = new JSONObject();
        try {
            String token = request.getParameter("token");
            String postId = request.getParameter("postId");
            if (StringUtils.isEmpty(token) || StringUtils.isEmpty(postId)) {
                json.put("code", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getValue());
                json.put("message", SystemStatusEnum.PARAMETER_CANNOT_BE_EMPTY.getName());
                return json.toString();
            }
            String isLogin = redis.opsForValue().get(token);
            if (StringUtils.isEmpty(isLogin)) {
                json.put("code", SystemStatusEnum.TOKEN_FAILURE.getValue());
                json.put("message", SystemStatusEnum.TOKEN_FAILURE.getName());
                return json.toString();
            }
            BpUser user = userService.getByToken(token);
            if (user == null) {
                json.put("code", SystemStatusEnum.USER_IS_NULL.getValue());
                json.put("message", SystemStatusEnum.USER_IS_NULL.getName());
                return json.toJSONString();
            }
            BpPost bpPost = new BpPost();
            bpPost.setId(postId);
            bpPost.setUserId(user.getId());
            bpPost.setStatus(CommonCode.CONTENT_IS_NORMAL.getValue());
            List<BpPost> postList = postService.findBySearch(bpPost);
            if (postList == null || postList.size() == 0) {
                json.put("code", SystemStatusEnum.NOT_DELETE_POST.getValue());
                json.put("message", SystemStatusEnum.NOT_DELETE_POST.getName());
                return json.toString();
            }
            BpPost post = postList.get(0);
            if (post != null) {
                post.setStatus(CommonCode.CONTENT_IS_DELETE.getValue());
                post.setSymbol(CommonCode.N.getValue());
                postService.update(post);
            }
            json.put("code", SystemStatusEnum.SUCCESS.getValue());
            json.put("message", SystemStatusEnum.SUCCESS.getName());
            return json.toString();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            json.put("code", SystemStatusEnum.SERVERERROR.getValue());
            json.put("message", SystemStatusEnum.SERVERERROR.getName());
        }
        return json.toString();
    }

    /**
     * 构建评论列表
     */
    private List<CommentsVO> commentsToVo(BpUser user, List<BpComments> commentsList) {
        List<CommentsVO> commentsVoList = new ArrayList<>();
        Integer praiseNum = 0;
        Integer commentsNum = 0;
        String isPraise = CommonCode.N.getValue();
        String isMyComments = CommonCode.N.getValue();
        for (BpComments comments : commentsList) {
            if (comments.getCommentsId().equals(comments.getId()) && comments.getType().equals(CommonCode.COMMENT_TYPE_D.getValue())) {
                praiseNum++;
            }
            if (comments.getCommentsId().equals(comments.getId()) && comments.getType().equals(CommonCode.COMMENT_TYPE_P.getValue())) {
                commentsNum++;
            }
            if (user != null) {
                if (comments.getType().equals(CommonCode.COMMENT_TYPE_D.getValue()) && comments.getCommentsUserId().equals(user.getId())) {
                    isPraise = CommonCode.Y.getValue();
                }
                if (comments.getType().equals(CommonCode.COMMENT_TYPE_P.getValue()) && comments.getCommentsUserId().equals(user.getId())) {
                    isMyComments = CommonCode.Y.getValue();
                }
            }
            CommentsVO commentsVO = new CommentsVO();
            commentsVO.setId(comments.getId());
            commentsVO.setType(comments.getType());
            commentsVO.setPostId(comments.getPostId());
            commentsVO.setCommentsId(comments.getCommentsId());
            commentsVO.setCommentsUserId(comments.getCommentsUserId());
            commentsVO.setContent(comments.getContent());
            commentsVO.setIsClassic(comments.getIsClassic());
            commentsVO.setIsTop(comments.getIsTop());
            commentsVO.setReleaseTime(comments.getReleaseTime());
            commentsVO.setUserInfo(getUserInfoVO(comments.getCommentsUserId()));
            commentsVO.setPraiseNum(praiseNum);
            commentsVO.setCommentsNum(commentsNum);
            commentsVO.setIsPraise(isPraise);
            commentsVO.setIsMyComments(isMyComments);
            commentsVoList.add(commentsVO);
        }
        return commentsVoList;
    }

    /**
     * 构建帖子详情
     * @throws
     */
    private PostVO getPostVo(BpPost post, BpUser user, List<CommentsVO> commentsVoList) {
        Integer praiseNum = 0;
        Integer commentsNum = 0;
        String isPraise = CommonCode.N.getValue();
        if (commentsVoList != null && commentsVoList.size() > 0) {
            for (CommentsVO vo : commentsVoList) {
                if (vo.getPostId().equals(post.getId()) && vo.getType().equals(CommonCode.COMMENT_TYPE_D.getValue())) {
                    praiseNum++;
                }
                if (vo.getPostId().equals(post.getId()) && vo.getType().equals(CommonCode.COMMENT_TYPE_P.getValue())) {
                    commentsNum++;
                }
                if (user != null) {
                    if (vo.getType().equals(CommonCode.COMMENT_TYPE_D.getValue()) && vo.getCommentsUserId().equals(user.getId())) {
                        isPraise = CommonCode.Y.getValue();
                    }
                }
            }
        }
        String userId = post.getUserId();
        PostVO postVo = new PostVO();
        postVo.setId(post.getId() == null ? "" : post.getId());
        postVo.setImages(post.getImages() == null || post.getImages() == "" ? new ArrayList<>() : Arrays.asList(post.getImages().split(",")));
        postVo.setContent(post.getContent() == null ? "" : post.getContent());
        postVo.setChannelId(post.getChannelId() == null ? "" : post.getChannelId());
        postVo.setChannelName(post.getChannelName() == null ? "" : post.getChannelName());
        postVo.setPraiseNum(praiseNum);
        postVo.setCommentsNum(commentsNum);
        postVo.setIsClassic(post.getIsClassic() == null ? "" : post.getIsClassic());
        postVo.setIsTop(post.getIsTop() == null ? "" : post.getIsTop());
        postVo.setReleaseTime(post.getReleaseTime() == null ? null : post.getReleaseTime());
        postVo.setIsPraise(isPraise);
        postVo.setUserInfo(getUserInfoVO(userId));
        return postVo;
    }

    /**
     * 构建用户信息
     */
    private UserInfoVO getUserInfoVO(String userId) {
    	BpUser user = userService.getById(userId);
        UserInfoVO vo = new UserInfoVO();
        if (user != null) {
            vo.setId(user.getId() == null ? "" : user.getId());
            vo.setUserPhoto(user.getUserPhoto() == null ? "" : user.getUserPhoto());
            vo.setNickName(user.getNickName() == null ? "" : user.getNickName());
            vo.setSex(user.getSex() == null ? "" : user.getSex());
            vo.setUserType(user.getUserType() == null ? "" : user.getUserType());
        }
        return vo;
    }

}
